package puc.redes.examples.server;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPServer1 {

	public static void main(String args[]) throws Exception {
		try {
			byte[] receiveData = new byte[1024];
			byte[] sendData = new byte[1024];

			DatagramSocket serverSocket = new DatagramSocket(2512);
			
			while (true) {

				receiveData = new byte[1024];

				DatagramPacket receivePacket = new DatagramPacket(receiveData,
						receiveData.length);

				System.out.println("Esperando un datagrama UDP");

				serverSocket.receive(receivePacket);

				String sentence = new String(receivePacket.getData());

				InetAddress IPAddress = receivePacket.getAddress();

				int port = receivePacket.getPort();

				System.out.println("De: " + IPAddress + ":" + port);
				System.out.println("Mensaje: " + sentence);

				String capitalizedSentence = sentence.toUpperCase();

				sendData = capitalizedSentence.getBytes();

				DatagramPacket sendPacket = new DatagramPacket(sendData,
						sendData.length, IPAddress, port);

				serverSocket.send(sendPacket);

			}

		} catch (SocketException ex) {
			System.out.println("Puerto UDP 2512 esta ocupado.");
			System.exit(1);
		}

	}
}
